package com.example.zjsr.service.impl;

import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.dao.InfoDao;
import com.example.zjsr.domain.*;
import com.example.zjsr.service.InfoService;
import com.example.zjsr.util.StringUtil;
import com.example.zjsr.util.WordFrequencyAnalyzer;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kennycason.kumo.WordFrequency;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InfoServiceImpl implements InfoService {

    @Autowired
    public InfoDao infoDao;

    @Override
    public ServerResponse getAnchors(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum,pageSize);
        List<Anchors> anchorsList=infoDao.getAnchors(keyword);
        PageInfo<Anchors> pageInfo=new PageInfo(anchorsList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse getAnchorsInfo(Integer pageNum, Integer pageSize, String anchorID) {
        PageHelper.startPage(pageNum,pageSize);
        List<AnchorsInfo> anchorsInfoList=infoDao.getAnchorsInfo(anchorID);
        PageInfo<AnchorsInfo> pageInfo=new PageInfo(anchorsInfoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getFruit(Integer pageNum, Integer pageSize,String keyword) {
        PageHelper.startPage(pageNum,pageSize);
        List<Fruit> fruitList=infoDao.getFruit(keyword);
        PageInfo<Fruit> fruitPageInfo=new PageInfo<>(fruitList);
        return ServerResponse.createBySuccess(fruitPageInfo);
    }

    @Override
    public ServerResponse getFruitInfo(Integer pageNum, Integer pageSize, Integer fruitId,Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        List<FruitInfo> fruitInfoList=infoDao.getFruitInfo(fruitId);
        if(status==0){
            for (int i = 0; i <10; i++) {
                int randomNumber=(int)(1+Math.random()*(fruitInfoList.size()-2+1));
                fruitInfoList.add(fruitInfoList.get(randomNumber));
            }
        }
        PageInfo<FruitInfo> fruitInfoPageInfo=new PageInfo<>(fruitInfoList);
        if(status==0){
//            fruitInfoPageInfo.setSize(fruitInfoList.size()+10);
            fruitInfoPageInfo.setTotal(fruitInfoList.size());
//            fruitInfoPageInfo.setEndRow(fruitInfoList.size()+10);
        }
        return ServerResponse.createBySuccess(fruitInfoPageInfo);
    }

    @Override
    public ServerResponse getFruitInfoEmpty(Integer pageNum, Integer pageSize, Integer fruitId) {
        PageHelper.startPage(pageNum,pageSize);
        List<FruitInfo> fruitInfoList=infoDao.getFruitInfoEmpty(fruitId);
//        for (int i = 0; i < fruitInfoList.size(); i++) {
//            FruitInfo fruitInfo=fruitInfoList.get(i);
//            if(null==fruitInfo.getLowSales()||null==fruitInfo.getInventory()||null==fruitInfo.getTotalSales()
//            ||null==fruitInfo.getFavorableRate()||null==fruitInfo.getPrice()||null==fruitInfo.getEvaluationLabel()){
//                fruitInfoList.remove(i);
//                i--;
//            }
//        }
        PageInfo<FruitInfo> fruitInfoPageInfo=new PageInfo<>(fruitInfoList);
        return ServerResponse.createBySuccess(fruitInfoPageInfo);
    }

    @Override
    public ServerResponse getFruitChart(Integer fruitId) {
        Fruit fruit=infoDao.getFruitChart(fruitId);
        String[] price=fruit.getPrice().split("，");//价格
        String[] score=fruit.getScore().split("，");//评分
        Double[] scoreDouble=new Double[score.length];
        for (int i = 0; i <score.length; i++) {
            scoreDouble[i]= Double.valueOf(score[i]);
        }
//        Arrays.sort(scoreDouble);
        int k=0;
        int sum=0;
        int[] yScoreDouble=new int[5];
        String[] xScoreDouble=new String[5];
        for (double i = 4.2; i <5.0; i=(double) Math.round(i*10+0.2*10)/10 ) {
            int num=0;
            for (int j = 0; j <scoreDouble.length; j++) {
                if(scoreDouble[j]>i&&scoreDouble[j]<=(i+0.2)){
                    num++;
                    sum++;
                }
            }
            k++;
            yScoreDouble[k]=num;
            xScoreDouble[k]=i+"-"+(double) Math.round(i*10+0.2*10)/10;
        }
        yScoreDouble[0]=12-sum;
        xScoreDouble[0]="4.2以下";
//        double min=scoreDouble[0];
//        double max=scoreDouble[scoreDouble.length-1];
//        double scoreInterval=(max-min)/5;
//        for (int i = 0; i <5; i++) {
//            int num=0;
//            for (int j = 0; j < scoreDouble.length; j++) {
//                if(scoreDouble[j]>min&&scoreDouble[j]<=(min+scoreInterval)){
//                    num++;
//                }
//            }
//            yScoreDouble[i]=num;
//            xScoreDouble[i]=min+"-"+(min+scoreInterval);
//            min=min+scoreInterval;
//        }
        String[] inventoryData=fruit.getInventoryData().split("，");//库存
        String[] salesVolume=fruit.getSalesVolume().split("，");//销量
        FruitChart fruitChart=new FruitChart();
        fruitChart.setPrice(price);
        fruitChart.setXScoreDouble(xScoreDouble);
        fruitChart.setYScoreDouble(yScoreDouble);
//        fruitChart.setScore(score);
        fruitChart.setInventoryData(inventoryData);
        fruitChart.setSalesVolume(salesVolume);
        return ServerResponse.createBySuccess(fruitChart);
    }

    @Override
    public ServerResponse getLivingProduct(Integer fruitId,String[] fruitMapping){
        /**
         * 评价 好评率
         */
        List<FruitInfo> favorableRateList=infoDao.getFavorableRate(fruitId);
        int sum=0;
        Integer[] favorableRateNums=new Integer[6];
        int x=1;
        for (int i = 90; i <100; i=i+2) {
            int num=0;
            for (int j = 0; j < favorableRateList.size(); j++) {
                FruitInfo fruitInfo=favorableRateList.get(j);
                    int favorableRate= (int) Math.ceil(Double.parseDouble(fruitInfo.getFavorableRate().substring(0,fruitInfo.getFavorableRate().lastIndexOf("."))));
                    if(favorableRate>i&&favorableRate<=i+2){
                        num++;
                }
            }
            favorableRateNums[x]=num;
            sum=sum+num;
            x++;
        }
        favorableRateNums[0]=favorableRateList.size()-sum;
        String[] favorableRateKey={"90%以下","90%-92%","92%-94%","94%-96%","96%-98%","98%-100%"};

        /**
         * 价格
         */
        List<FruitInfo> lowSalesList=infoDao.getLowSales(fruitId);
        int maxLowSales= (int) Math.round(lowSalesList.get(lowSalesList.size()-1).getLowSales());
        int minLowSales= (int) Math.round(lowSalesList.get(0).getLowSales());
        int lowSalesSection=(maxLowSales-minLowSales)/10;
        int lowSalesLow=0;
        int lowSalesHigh=minLowSales;
        int lowSalesK=0;//库存区间不为0的值有几个
        String[] lowSalesKey=new String[10];
        int[] lowSalesValue=new int[10];
        int maxLowSalesValue=0;
        String maxLowSalesKey="";
        for (int i = 0; i <10; i++) {
            lowSalesHigh=lowSalesHigh+lowSalesSection;
            int num=0;
            for (int j = 0; j <lowSalesList.size(); j++) {
                if(lowSalesList.get(j).getLowSales()>=lowSalesLow&&lowSalesList.get(j).getLowSales()<=lowSalesHigh){
                    num++;
                }
            }
            if(num!=0){
//                inventoryMap.put(low+"-"+high,num);
                lowSalesKey[lowSalesK]=lowSalesLow+"-"+lowSalesHigh;
                lowSalesValue[lowSalesK]=num;
                lowSalesK++;
                if(maxLowSalesValue<num){
                    maxLowSalesValue=num;
                    maxLowSalesKey=lowSalesLow+"-"+lowSalesHigh;
                }
            }
            lowSalesLow=lowSalesHigh;
        }
        List<String> lowSalesKeyList=new ArrayList<>();
        for (String key : lowSalesKey) {
            if(null!=key){
                lowSalesKeyList.add(key);
            }
        }
        List<Integer> lowSalesValueList=new ArrayList<>();
        for (Integer value : lowSalesValue) {
            if(0!=value){
                lowSalesValueList.add(value);
            }
        }
        /**
         * 总销量
         */
        List<FruitInfo> salesList=infoDao.getSales(fruitId);
        int maxSales=salesList.get(salesList.size()-1).getTotalSales();
        int minSales=salesList.get(0).getTotalSales();
        int salesSection=(maxSales-minSales)/10;
        int salesLow=0;
        int salesHigh=minSales;
        int salesK=0;//库存区间不为0的值有几个
        String[] salesKey=new String[10];
        int[] salesValue=new int[10];
        for (int i = 0; i <10; i++) {
            salesHigh=salesHigh+salesSection;
            int num=0;
            for (int j = 0; j <salesList.size(); j++) {
                if(salesList.get(j).getTotalSales()>=salesLow&&salesList.get(j).getTotalSales()<=salesHigh){
                    num++;
                }
            }
            if(num!=0){
//                inventoryMap.put(low+"-"+high,num);
                salesKey[salesK]=salesLow+"-"+salesHigh;
                salesValue[salesK]=num;
                salesK++;
            }
            salesLow=salesHigh;
        }
        List<String> salesKeyList=new ArrayList<>();
        for (String key : salesKey) {
            if(null!=key){
                salesKeyList.add(key);
            }
        }
        List<Integer> salesValueList=new ArrayList<>();
        for (Integer value : salesValue) {
            if(0!=value){
                salesValueList.add(value);
            }
        }
        /**
         * 库存(通过查询区间来查询库存进行分区)
         */
//        Map<String,Integer> inventoryMap=new HashMap<>();
        List<FruitInfo> inventoryList=infoDao.getInventory(fruitId);
        int maxInventory=inventoryList.get(inventoryList.size()-1).getInventory();
        int minInventory=inventoryList.get(0).getInventory();
        int inventorySection=(maxInventory-minInventory)/10;
        int low=0;
        int high=minInventory;
        int k=0;//库存区间不为0的值有几个
        String[] inventoryKey=new String[10];
        int maxInventoryValue=0;
        String maxInventoryKey="";
        int[] inventoryValue=new int[10];
        for (int i = 0; i <10; i++) {
            high=high+inventorySection;
            int num=0;
            for (int j = 0; j <inventoryList.size(); j++) {
                if(inventoryList.get(j).getInventory()>=low&&inventoryList.get(j).getInventory()<=high){
                    num++;
                }
            }
            if(num!=0){
//                inventoryMap.put(low+"-"+high,num);
                inventoryKey[k]=low+"-"+high;
                inventoryValue[k]=num;
                if(maxInventoryValue<num){
                    maxInventoryValue=num;
                    maxInventoryKey=low+"-"+high;
                }
                k++;
            }
            low=high;
        }
        List<String> inventoryKeyList=new ArrayList<>();
        for (String key : inventoryKey) {
            if(null!=key){
                inventoryKeyList.add(key);
            }
        }
        List<Integer> inventoryValueList=new ArrayList<>();
        for (Integer value : inventoryValue) {
            if(0!=value){
                inventoryValueList.add(value);
            }
        }
        /**
         * 省份
         */
        List<ProvinceMap> provinceMaps=infoDao.getProvinceMap(fruitId);
        provinceMaps.forEach(provinceMap -> {
            provinceMap.setProvince(provinceMap.getProvince().replace("省",""));
            provinceMap.setProvince(provinceMap.getProvince().replace("市",""));
//            provinceMap.getProvince().replace("省","");
//            provinceMap.getProvince().replace("市","");
        });
        /**
         *评价(根据数据量排序)
         */
        Map<String,Integer> evaluationLabelMap=new HashMap<>();
        for (FruitInfo fruitInfo : inventoryList) {
            if(null!=fruitInfo.getEvaluationLabel()){
                String[] everyEvaluationLabel=fruitInfo.getEvaluationLabel().split(";");
                for (int i = 0; i < everyEvaluationLabel.length; i++) {
                    if(everyEvaluationLabel[i].contains("(")){
                        everyEvaluationLabel[i]=everyEvaluationLabel[i].trim();
                        String evaluationLabelKey=everyEvaluationLabel[i].substring(0,everyEvaluationLabel[i].lastIndexOf("("));
                        Integer evaluationLabelValue= Integer.valueOf(everyEvaluationLabel[i].substring(everyEvaluationLabel[i].lastIndexOf("(")+1,everyEvaluationLabel[i].lastIndexOf(")")));
                        if(null!=evaluationLabelMap.get(evaluationLabelKey)){
                            Integer oldValue=evaluationLabelMap.get(evaluationLabelKey);
                            evaluationLabelMap.put(evaluationLabelKey,evaluationLabelValue+oldValue);
                        }else{
                            evaluationLabelMap.put(evaluationLabelKey,evaluationLabelValue);
                        }
                    }
                }
            }
        }
        List<LabelFrequency> labelFrequencyList=new ArrayList<>();
        for (String label : evaluationLabelMap.keySet()) {
            LabelFrequency labelFrequency=new LabelFrequency();
            labelFrequency.setWord(label);
            labelFrequency.setFrequency(evaluationLabelMap.get(label));
            labelFrequencyList.add(labelFrequency);
        }
        /**
         * 根据词频数量来进行排序
         */
        labelFrequencyList=labelFrequencyList.stream().sorted(Comparator.comparing(LabelFrequency::getFrequency).reversed()).collect(Collectors.toList());
        LivingProductResult livingProductResult=new LivingProductResult();
        livingProductResult.setMaxLowSalesKey(maxLowSalesKey);
        livingProductResult.setMaxInventoryKey(maxInventoryKey);

        /**
         * 性别
         */
        List<TimeResult> sexFruitInfoList=infoDao.getSexFruitInfo(fruitId);
        /**
         * 根据性别数量来进行排序
         */
        sexFruitInfoList=sexFruitInfoList.stream().sorted(Comparator.comparing(TimeResult::getValue).reversed()).collect(Collectors.toList());
        String[] sexKey=new String[sexFruitInfoList.size()];
        int[] sexValue=new int[sexFruitInfoList.size()];
        for (int i = 0; i < sexFruitInfoList.size(); i++) {
            sexKey[i]=sexFruitInfoList.get(i).getName();
            sexValue[i]=sexFruitInfoList.get(i).getValue();
        }
        /**
         * 年龄
         */
        List<TimeResult> ageFruitInfoList=infoDao.getAgeFruitInfo(fruitId);

        /**
         * 根据年龄区分数量来进行排序
         */
        ageFruitInfoList=ageFruitInfoList.stream().sorted(Comparator.comparing(TimeResult::getValue).reversed()).collect(Collectors.toList());
        String[] ageKey=new String[ageFruitInfoList.size()];
        int[] ageValue=new int[ageFruitInfoList.size()];
        for (int i = 0; i < ageFruitInfoList.size(); i++) {
            ageKey[i]=ageFruitInfoList.get(i).getName();
            ageValue[i]=ageFruitInfoList.get(i).getValue();
        }
        /**
         * 特点
         */
        Map<String,Integer> characterMap=new HashMap<>();
        List<FruitInfo> characterFruitInfoList=infoDao.getCharacterFruitInfo(fruitId);
        for (FruitInfo fruitInfo : characterFruitInfoList) {
            String[] characterArray=fruitInfo.getCharacters().split(";");
            for (String character : characterArray) {
                if(characterMap.containsKey(character)){
                    int num=characterMap.get(character);
                    characterMap.put(character,++num);
                }else{
                    characterMap.put(character,0);
                }
            }
        }
        List<LabelFrequency> characterFrequencyList=new ArrayList<>();
        for (String character : characterMap.keySet()) {
            LabelFrequency labelFrequency=new LabelFrequency();
            labelFrequency.setWord(character);
            labelFrequency.setFrequency(characterMap.get(character));
            characterFrequencyList.add(labelFrequency);
        }
        /**
         * 根据数据量大小从小到大排序
         */
        characterFrequencyList=characterFrequencyList.stream().sorted(Comparator.comparing(LabelFrequency::getFrequency).reversed()).collect(Collectors.toList());
        
        for (int i = 0; i < fruitMapping.length; i++) {
                /**
                 * 1是库存
                 */
            if(Integer.parseInt(fruitMapping[i])==1){
                livingProductResult.setInventoryKey(inventoryKeyList.toArray(new String[k]));
                livingProductResult.setInventoryValue(inventoryValueList.toArray(new Integer[k]));
            }else if(Integer.parseInt(fruitMapping[i])==2){
                /**
                 * 2是评价
                 */
                livingProductResult.setLabelFrequency(labelFrequencyList);
            }else if(Integer.parseInt(fruitMapping[i])==3){
                /**
                 * 3是评分
                 */
                livingProductResult.setFavorableRateValue(favorableRateNums);
                livingProductResult.setFavorableRateKey(favorableRateKey);
            }
            else if(Integer.parseInt(fruitMapping[i])==4){
                /**
                 * 4是价格
                 */
                livingProductResult.setLowSalesKey(lowSalesKeyList.toArray(new String[lowSalesK]));
                livingProductResult.setLowSalesValue(lowSalesValueList.toArray(new Integer[lowSalesK]));
            }else if(Integer.parseInt(fruitMapping[i])==5){
                /**
                 * 5是销量
                 */
                livingProductResult.setSalesKey(salesKeyList.toArray(new String[salesK]));
                livingProductResult.setSalesValue(salesValueList.toArray(new Integer[salesK]));
            }else if(Integer.parseInt(fruitMapping[i])==6){
                /**
                 * 6是地点
                 */
                livingProductResult.setProvinceMaps(provinceMaps);
            }else if(Integer.parseInt(fruitMapping[i])==7){
                /**
                 * 7是性别
                 */
                livingProductResult.setSexKey(sexKey);
                livingProductResult.setSexValue(sexValue);
                livingProductResult.setMaxSex(sexKey[0]);
            }else if(Integer.parseInt(fruitMapping[i])==8){
                /**
                 * 8是年龄
                 */
                livingProductResult.setAgeKey(ageKey);
                livingProductResult.setAgeValue(ageValue);
                livingProductResult.setMaxAge(ageKey[0]);
            }else if(Integer.parseInt(fruitMapping[i])==9){
                /**
                 * 9是特点
                 */
                livingProductResult.setCharacterFrequency(characterFrequencyList);
            }
        }
        return ServerResponse.createBySuccess(livingProductResult);
    }


    @Override
    public ServerResponse getFruitPicture(Integer fruitId) {
        String path=infoDao.getFruitPicture(fruitId);
        return ServerResponse.createBySuccess(path);
    }

    @Override
    public ServerResponse getAnchorsCharts(String anchorID) {
        List<AnchorsInfo> anchorsInfoList=infoDao.getAnchorsCharts(anchorID);
        List<TimeResult> beginDateList=infoDao.getBeginDate(anchorID);
        List<TimeResult> endDateList=infoDao.getEndDate(anchorID);
        /**
         * 粉丝
         */
        String[] anchorsFansKey=new String[10];
        String[] anchorsFansValue=new String[10];
        /**
         * 观看人数
         */
        String[] viewsNumsKey=new String[10];
        String[] viewsNumsValue=new String[10];
        /**
         * 直播宝贝均价
         */
        String[] treasureAvgKey=new String[10];
        String[] treasureAvgValue=new String[10];
        /**
         * 销量
         */
        String[] salesVolumeKey=new String[10];
        String[] salesVolumeValue=new String[10];
        /**
         * 销售额
         */
        String[] salesKey=new String[10];
        String[] salesValue=new String[10];
        for (int i = 0; i <10; i++) {
            anchorsFansKey[i]=anchorsInfoList.get(i).getInfoDate();
            anchorsFansValue[i]=anchorsInfoList.get(i).getInfoFansNumber().replaceAll(",","");
            viewsNumsKey[i]=anchorsInfoList.get(i).getInfoDate();
            viewsNumsValue[i]=anchorsInfoList.get(i).getViewNums().replaceAll(",","");
            treasureAvgKey[i]=anchorsInfoList.get(i).getInfoDate();
            String treasureAvg=anchorsInfoList.get(i).getTreasureAvg().replaceAll(",","");
            treasureAvgValue[i]=treasureAvg.substring(0,treasureAvg.lastIndexOf("."));
            salesVolumeKey[i]=anchorsInfoList.get(i).getInfoDate();
            salesVolumeValue[i]=anchorsInfoList.get(i).getSalesVolume().replaceAll(",","");
            salesKey[i]=anchorsInfoList.get(i).getInfoDate();
            String sales=anchorsInfoList.get(i).getSales().replaceAll(",","");
            salesValue[i]=sales.substring(0,sales.length()-1);
        }
        AnchorsCharts anchorsCharts=new AnchorsCharts();
        anchorsCharts.setAnchorsFansKey(anchorsFansKey);
        anchorsCharts.setAnchorsFansValue(anchorsFansValue);
        anchorsCharts.setSalesKey(salesKey);
        anchorsCharts.setSalesValue(salesValue);
        anchorsCharts.setSalesVolumeKey(salesVolumeKey);
        anchorsCharts.setSalesVolumeValue(salesVolumeValue);
        anchorsCharts.setTreasureAvgKey(treasureAvgKey);
        anchorsCharts.setTreasureAvgValue(treasureAvgValue);
        anchorsCharts.setViewsNumsKey(viewsNumsKey);
        anchorsCharts.setViewsNumsValue(viewsNumsValue);
        anchorsCharts.setBeginDateList(beginDateList);
        anchorsCharts.setEndDateList(endDateList);
        anchorsCharts.setEndDate(endDateList.get(0).getName());
        anchorsCharts.setBeginDate(beginDateList.get(0).getName());
        return ServerResponse.createBySuccess(anchorsCharts);
    }
}
